package com.gopay.cron.service.trans;

import java.math.BigDecimal;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gopay.common.cipher.utils.LoggerMaskUtils;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.rcs.TranDirection;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.acps.model.AcctMastBean;
import com.gopay.common.domain.rcs.RcsGAcctLimitStatistics;
import com.gopay.common.domain.rcs.RcsTransLimitStatistics;
import com.gopay.common.domain.rcs.req.RcsTransLimitRequest;
import com.gopay.common.domain.rcs.req.RcsTransLimitRequest.RequestType;
import com.gopay.common.domain.rcs.res.RcsTransLimitResponse;
import com.gopay.common.domain.solution.SolutionRequest;
import com.gopay.common.domain.solution.SolutionResponse;
import com.gopay.common.domain.solution.TranLimitReq;
import com.gopay.common.domain.solution.TranLimitRes;
import com.gopay.common.exception.GopayException;
import com.gopay.common.rcs.manager.translimit.RcsGAcctLimitStatisticsManager;
import com.gopay.common.rcs.service.translimit.RcsTransLimitService;
import com.gopay.common.rcs.vo.RcsTransLimitView;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.acps.service.AcctTransRemoteService;
import com.gopay.remote.solution.SolutionRemoteService;

@Service("rcsTransLimitClientService")
public class RcsTransLimitClientService {

	private static Logger logger = LoggerFactory.getLogger("RcsTransLimitClient");
    @Resource(name = "tranLimitConfClient")
    private SolutionRemoteService tranLimitConfClient;
    
    @Resource(name = "rcsTransLimitService")
    private RcsTransLimitService rcsTransLimitService;
    
    @Resource(name = "acctMastService")
    protected AcctTransRemoteService acctMastService;
    
    @Resource(name = "rcsGAcctLimitStatisticsManager")
    private RcsGAcctLimitStatisticsManager rcsGAcctLimitStatisticsManager;
    
    public RcsTransLimitView getLimitConfig(String acctId,TranDirection dir,IntTxnCd intTxnCd){
    	if(StringUtils.isBlank(acctId))
    		return null;
    	RcsTransLimitView view = new RcsTransLimitView();
    	TranLimitReq req = new TranLimitReq();
        req.setAcctType(acctId.substring(8, 10));
        req.setIntTxnCd(intTxnCd);
        req.setTranDirection(dir);
        AcctMastBean acct = acctMastService.getAccount(acctId);
        req.setAcctProd(acct.getProdCode());
        req.setCustId(acct.getCustId());
        SolutionRequest request = new SolutionRequest();
        request.setAcctId(acctId);
        request.setSequence(System.currentTimeMillis());
        request.setTimestamp(DateUtils.getSystemDate());
        request.setRequest(req);
        SolutionResponse res = tranLimitConfClient.resolve(request);
        if (null == res || false == res.isSucceed()) {
        	logger.error(intTxnCd+"获取额度：SolutionResponse is null or failed ,request data :" + JSONObject.fromObject(request).toString());
            return null;
        }
        TranLimitRes tres =  (TranLimitRes) res.getResponse();
        view.setAcctId(acctId);
        view.setAcctProd(req.getAcctProd());
        view.setCustId(req.getCustId());
        view.setIntTxnCd(intTxnCd);
        view.setTranDirection(dir);
        view.setTranLimitRes(tres);
        return view;
    }
    
    
    public boolean checkAmtLimit(RcsTransLimitView view,BigDecimal tranAmt) throws GopayException{
    	if(view==null) 
    		return true;
    	
    	RcsTransLimitRequest request = new RcsTransLimitRequest();
    	request.setCustTranLimitConf(view.getTranLimitRes());
    	request.setAcctProd(view.getAcctProd());
    	request.setCustId(view.getCustId());
    	request.setIntTxnCd(view.getIntTxnCd());
    	request.setRequestType(RequestType.check);
    	request.setTranAmts(tranAmt);
    	request.setTransDate(DateUtils.getCurrDate("yyyyMMdd"));
    	request.setTranDirection(view.getTranDirection());
    	logger.info(view.getIntTxnCd()+"校验额度请求：rcsTransLimitProcess request data :" + JSONObject.fromObject(request).toString());
    	RcsTransLimitResponse resp = rcsTransLimitService.rcsTransLimitProcess(request);
    	logger.info(view.getIntTxnCd()+"校验额度响应：RcsTransLimitResponse data :" + JSONObject.fromObject(resp).toString());
    	if(!StringUtils.equals(resp.getProcCode(), ProcCodeConstants.PROC_CODE_200S1000)){
    		return false;
    	}
    	return true;
    }
    public void checkAmtLimit(RcsTransLimitView view,BigDecimal tranAmt,String pbocBankCode,String bankName,String bankAcctNum,String bankAcctName) throws GopayException{
    	if(view==null) 
    		return ;
    	
    	RcsTransLimitRequest request = new RcsTransLimitRequest();
    	request.setCustTranLimitConf(view.getTranLimitRes());
    	request.setAcctProd(view.getAcctProd());
    	request.setCustId(view.getCustId());
    	request.setIntTxnCd(view.getIntTxnCd());
    	request.setRequestType(RequestType.check);
    	request.setTranAmts(tranAmt);
    	request.setTransDate(DateUtils.getCurrDate("yyyyMMdd"));
    	request.setTranDirection(view.getTranDirection());
    	
    	request.setPbocBankCode(pbocBankCode);
    	request.setBankName(bankName);
    	request.setBankAcctNum(bankAcctNum);
    	request.setBankAcctName(bankAcctName);
//    	logger.info(view.getIntTxnCd()+"校验额度请求：rcsTransLimitProcess request data :" + JSONObject.fromObject(request).toString());
    //  修改日誌的輸出，ssj 2017/01/12 pci需求改造，銀行卡號掩碼輸出
    	logger.info(view.getIntTxnCd()+"校验额度请求：rcsTransLimitProcess request data :" + 	LoggerMaskUtils.maskString(request.toString()));
    	RcsTransLimitResponse resp = rcsTransLimitService.rcsTransLimitProcess(request);
    	logger.info(view.getIntTxnCd()+"校验额度响应：RcsTransLimitResponse data :" + JSONObject.fromObject(resp).toString());
    	if(!StringUtils.equals(resp.getProcCode(), ProcCodeConstants.PROC_CODE_200S1000)){
    		throw new GopayException(resp.getProcCode(),resp.getProcCodeMsg());
    	}
    }
    
    public RcsTransLimitStatistics findRcsGAcctLimitStatistics(
            RcsTransLimitView view) {
        if(null == view){
            return null;
        }
        try {
            RcsGAcctLimitStatistics limitStatistics = rcsGAcctLimitStatisticsManager
                    .getTransLimitStatistics(view.getCustId(),
                            view.getAcctProd(), view.getIntTxnCd(),
                            view.getTranDirection(), DateUtils.getCurrDate("yyyyMMdd"));
            return limitStatistics;
        } catch (Exception e) {
            logger.error("获取客户累计额度统计信息异常：" + view, e);
        }
        return null;
    }
    
    public BigDecimal getOnceLimit(RcsTransLimitView view){
        
        if(null == view){
            return null;
        }
        
        TranLimitRes limitConf = view.getTranLimitRes();
        return limitConf.getOnceLimit();
    }
    
    public BigDecimal getDayLimit(RcsTransLimitView view){
        
        if(null == view){
            return null;
        }
        
        TranLimitRes limitConf = view.getTranLimitRes();
        return limitConf.getDayLimit();
    }
    
    public long getDayTimes(RcsTransLimitView view){
        
        if(null == view){
            return -1;
        }
        
        TranLimitRes limitConf = view.getTranLimitRes();
        return limitConf.getDayTimes();
    }
   
}
